import { useState } from 'react';
import type { Model } from '../types/chat';
import './ModelSelector.css';

interface ModelSelectorProps {
  models: Model[];
  selectedModel: string;
  onModelChange: (modelId: string) => void;
}

export function ModelSelector({ models, selectedModel, onModelChange }: ModelSelectorProps) {
  const [isOpen, setIsOpen] = useState(false);

  const selectedModelData = models.find((m) => m.id === selectedModel) || models[0];

  return (
    <div className="model-selector">
      <button
        className="model-selector-button"
        onClick={() => setIsOpen(!isOpen)}
        aria-label="选择模型"
      >
        <span className="model-selector-label">模型:</span>
        <span className="model-selector-value">{selectedModelData?.name || '未选择'}</span>
        <span className={`model-selector-arrow ${isOpen ? 'open' : ''}`}>▼</span>
      </button>
      {isOpen && (
        <>
          <div className="model-selector-overlay" onClick={() => setIsOpen(false)} />
          <div className="model-selector-dropdown">
            {models.map((model) => (
              <button
                key={model.id}
                className={`model-selector-option ${
                  selectedModel === model.id ? 'selected' : ''
                }`}
                onClick={() => {
                  onModelChange(model.id);
                  setIsOpen(false);
                }}
              >
                <div className="model-selector-option-name">{model.name}</div>
                {model.description && (
                  <div className="model-selector-option-desc">{model.description}</div>
                )}
                <div className="model-selector-option-provider">{model.provider}</div>
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

